﻿// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the 
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

namespace BaseLibrary
{
    public class AlwaysOnTopBehavior : TargetedTriggerAction<CheckBox>
    {
        CheckBox _element;

        protected override void OnAttached()
        {
            _element = this.AssociatedObject as CheckBox;
                
            // Works only out-of-browser
            if (Application.Current.IsRunningOutOfBrowser)
            {
                _element.Unchecked += new RoutedEventHandler(_element_Unchecked);
                _element.Checked += new RoutedEventHandler(_element_Checked);

            }
            else
            {
                _element.Visibility = Visibility.Collapsed;
            }
            base.OnAttached();
        }

        protected override void OnDetaching()
        {
            _element.Unchecked -= _element_Unchecked;
            _element.Checked -= _element_Checked;
                
            base.OnDetaching();
        }

        void _element_Checked(object sender, RoutedEventArgs e)
        {
            CheckState();
        }

        private void CheckState()
        {
            if (Application.Current.IsRunningOutOfBrowser)
            {
                Application.Current.MainWindow.TopMost = _element.IsChecked.HasValue ? _element.IsChecked.Value : false;
            }
            else
            {
                _element.Visibility = Visibility.Collapsed;
            }
        }

        void _element_Unchecked(object sender, RoutedEventArgs e)
        {
            CheckState();
        }

        protected override void Invoke(object o)
        {
        }
    }
}
